package face.pay.cpn.activity.service.impl;

import com.alibaba.fastjson.JSONArray;
import face.pay.cpn.AbstractApiService;
import face.pay.cpn.activity.service.ICpnCardInfoService;
import face.pay.cpn.utils.request.RequestParam;
import face.pay.cpn.utils.response.ErrorCode;
import face.pay.cpn.utils.response.ResponseMessage;
import face.pay.dao.CpnCardInfoDao;
import face.pay.entity.CpnMarketInfo;
import face.pay.vo.VoBaseCardInfo;
import face.pay.vo.VoCpnCardInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class CpnCardInfoServiceimpl extends AbstractApiService implements ICpnCardInfoService {


    @Autowired
    private CpnCardInfoDao cpnCardInfoDao;


    /**
     * 查找活动的卡券
     *
     * @param jsonData
     * @return
     */
    @Override
    public ResponseMessage queryCardInfo(String jsonData) {
        return doApi(jsonData);
    }

    @Override
    public ResponseMessage doService(CpnMarketInfo cpnMarketInfo, RequestParam requestParam) throws Exception {

        List<Integer> activityIdList = null;
        try {
            activityIdList = JSONArray.parseArray(requestParam.getData().get("activityIdList")).toJavaList(Integer.class);
        } catch (Exception e) {
            log.warn("参数有误market_code:{}", cpnMarketInfo.getMarket_code());
            return ResponseMessage.createParamFail();
        }

        if (activityIdList.size() == 0) {
            return ResponseMessage.createFail(ErrorCode.PARAM_FAIL_CODE, "每次至少查1条数据");
        }

        if (activityIdList.size() > 50) {
            return ResponseMessage.createFail(ErrorCode.PARAM_FAIL_CODE, "每次最多查50条数据");
        }
        log.info("开始查找活动卡券market_id:{}", cpnMarketInfo.getId());
        List<VoCpnCardInfo> cardlist = this.cpnCardInfoDao.getVoCpnCardInfoList(activityIdList);

        Map<Integer, List<VoCpnCardInfo>> cardGroup = cardlist.stream().collect(Collectors.groupingBy(VoCpnCardInfo::getActivityId));

        ArrayList<VoBaseCardInfo> voBaseCardData = new ArrayList<>();

        for (Integer activityId : activityIdList) {
            VoBaseCardInfo baseCardInfo = new VoBaseCardInfo();
            baseCardInfo.setActivityId(activityId);
            baseCardInfo.setCardList(cardGroup.get(activityId));
            voBaseCardData.add(baseCardInfo);
        }
        log.info("查找活动卡券结束market_id:{} 共: {} 条", cpnMarketInfo.getId(), activityIdList.size());
        return ResponseMessage.createSuccess(null, voBaseCardData);
    }


}
